package nevo.core;

import java.io.*;
import java.util.*;

import nevo.core.*;

public class Utilities
{
	public static Double[] fileToArray(String fpath) throws Exception
	{
		File f = new File(fpath);
		if (!f.exists()) throw new FileNotFoundException(fpath);
		List<Double> samples = new ArrayList<Double>();
		InputStreamReader isr = new FileReader(f);
		BufferedReader reader = new BufferedReader(isr);		
		
		String line;
		int indx = 0;
		while ((line = reader.readLine()) != null) {
			samples.add(indx++, Double.parseDouble(line));			
		}
		Double[] s = new Double[samples.size()];
		for (int k = 0; k < s.length; k++)  s[k] = samples.get(k);
		
		return s;
	}
	
	public static void matrixToFile(Double[][] matrix, String fpath) throws Exception
	{
		int nrows = matrix.length;
		int ncols = matrix[0].length;
		
		StringBuffer buf = new StringBuffer();
		int k, j;
		for (k = 0; k < nrows; k++) {
			buf.append(matrix[k][0]);
			for (j = 1; j < ncols; j++)  buf.append(" " + matrix[k][j]);
			buf.append("\n");			
		}
		
		File f = new File(fpath);
		FileWriter fw = new FileWriter(f);
		fw.write(buf.toString());
		fw.close();
	}
	
	public static void vectorToFile(Double[] v, String fpath) throws Exception
	{
		StringBuffer buf = new StringBuffer();
		int k;
		for (k = 0; k < v.length; k++) {
			buf.append(v[k]);			
			buf.append("\n");			
		}
		
		File f = new File(fpath);
		FileWriter fw = new FileWriter(f);
		fw.write(buf.toString());
		fw.close();
	}
	
	public static int runOptimization(Optimizer op, double maxresidual, int maxiterations) throws Exception
	{	
		int numiter = 0;
		Model model = op.getModel();
		ObjectiveFunction func = op.getObjectiveFunction();
		
		double min = 1e50;
      IRecord irec = null;
		for (; numiter < maxiterations; numiter++) {			
			irec = op.iterate(irec);
			List<IRecord> estimates = op.getCurrentEstimates();
			min = 1e50;
			double val = min;
			for (IRecord est : estimates) {
				val = est.getValue();
				if (val < min) min = val;
			}
			if (min <= maxresidual) break;
		}	
		
		return numiter;
	}
	
	public static Double[][] zerosMatrix(int nrows, int ncols)
	{
		Double[][] mat = new Double[nrows][ncols];
		
		for (int k = 0; k < nrows; k++) {
			for (int j = 0; j < ncols; j++) {
				mat[k][j] = 0.0;
			}
		}
		return mat;
	}
}
